package com.ews.onlineexchange.service;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;

import javax.inject.Inject;
import javax.mail.Address;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;

import org.apache.commons.lang3.StringUtils;
import org.jboss.logging.Logger;

import com.ews.onlineexchange.exception.EmailException;
import com.ews.onlineexchange.util.Config;
import com.ews.onlineexchange.util.PropertiesUtil;
import com.sun.mail.smtp.SMTPMessage;

/**
 * @author wcq
 */

public class EmailSender implements Serializable {
	private static final long	serialVersionUID	= 1L;
	private static final Logger	logger				= Logger.getLogger(EmailSender.class);
	
	@Inject
	Config config;
	/**
	 * @param address
	 *            收件人的邮箱
	 * @param subject
	 *            邮件主题显示内容
	 * @param textBody
	 *            纯文字
	 * @param htmlBody
	 *            含HTML元素的内容，如果htmlBody不为空时，即使textBody不为空，邮件内容也会显示htmlBody的内容
	 * @throws EmailException
	 */
	public  void send(String address, String subject, String textBody, String htmlBody) throws EmailException {
		Transport transport = null;
		try {
			Properties props = new Properties();
			props.setProperty("mail.smtp.host", config.getProperty("com.ews.onlineExchange.email.host"));
			props.setProperty("mail.smtp.localhost", config.getProperty("com.ews.onlineExchange.email.host"));
			boolean auth = "true".equals(config.getProperty("com.ews.onlineExchange.email.auth"));
			if (auth) {
				props.setProperty("mail.smtp.auth", "true");
			}

			props.setProperty("mail.smtp.timeout", "10000");
			props.setProperty("mail.smtp.connectiontimeout", "10000");
			//props.setProperty("mail.smtp.port", config.getProperty("com.ews.onlineExchange.email.port"));
//			props.setProperty("mail.smtp.sendpartial", "true");
			String from = config.getProperty("com.ews.onlineExchange.email.from");
			String fromDisplayName = config.getProperty("com.ews.onlineExchange.email.fromDisplayName");
			String replyTo = "";
			String replyToDisplayName = "";
			String envelopeFrom = "";
			Session session = Session.getInstance(props);
			Multipart multipart = new MimeMultipart("alternative");

			if (!StringUtils.isBlank(textBody)) {
				MimeBodyPart textPart = new MimeBodyPart();
				textPart.setText(textBody, "UTF-8");
				multipart.addBodyPart(textPart);
			}

			if (!StringUtils.isBlank(htmlBody)) {
				MimeBodyPart htmlPart = new MimeBodyPart();
				htmlPart.setContent(htmlBody, "text/html; charset=UTF-8");
				multipart.addBodyPart(htmlPart);
			}
			SMTPMessage msg = new SMTPMessage(session);
			msg.setFrom(toInternetAddress(from, fromDisplayName));

			msg.setReplyTo(new Address[] { toInternetAddress(from, fromDisplayName) });
			if (replyTo != null && !replyTo.isEmpty()) {
				msg.setReplyTo(new Address[] { toInternetAddress(replyTo, replyToDisplayName) });
			}
			if (envelopeFrom != null && !envelopeFrom.isEmpty()) {
				msg.setEnvelopeFrom(envelopeFrom);
			}

			msg.setHeader("To", address);
			msg.setSubject(subject, "utf-8");
			msg.setContent(multipart);
			msg.saveChanges();
			msg.setSentDate(new Date());

			transport = session.getTransport("smtp");
			if (auth) {
				transport.connect(config.getProperty("com.ews.onlineExchange.email.user"),
						config.getProperty("com.ews.onlineExchange.email.password"));
			} else {
				transport.connect();
			}
			transport.sendMessage(msg, new InternetAddress[] { toInternetAddress(address, address) });
		} catch (MessagingException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} finally {
			if (transport != null) {
				try {
					transport.close();
				} catch (MessagingException e) {
					logger.warn("Failed to close transport", e);
				}
			}
		}
	}
	/**
	 * 在阿里云监听中 使用 config为null
	 * @param address
	 * @param subject
	 * @param textBody
	 * @param htmlBody
	 * @throws EmailException
	 */
	public  void send_1(String address, String subject, String textBody, String htmlBody) throws EmailException {
		Transport transport = null;
		try {
			Properties props = new Properties();
			PropertiesUtil util = new PropertiesUtil("/config.properties");
			props.setProperty("mail.smtp.host", util.getProperty("com.ews.onlineExchange.email.host"));
			props.setProperty("mail.smtp.localhost", util.getProperty("com.ews.onlineExchange.email.host"));
			boolean auth = "true".equals(util.getProperty("com.ews.onlineExchange.email.auth"));
			if (auth) {
				props.setProperty("mail.smtp.auth", "true");
			}

			props.setProperty("mail.smtp.timeout", "10000");
			props.setProperty("mail.smtp.connectiontimeout", "10000");
			//props.setProperty("mail.smtp.port", config.getProperty("com.ews.onlineExchange.email.port"));
//			props.setProperty("mail.smtp.sendpartial", "true");
			String from = util.getProperty("com.ews.onlineExchange.email.from");
			String fromDisplayName = util.getProperty("com.ews.onlineExchange.email.fromDisplayName");
			String replyTo = "";
			String replyToDisplayName = "";
			String envelopeFrom = "";
			Session session = Session.getInstance(props);
			Multipart multipart = new MimeMultipart("alternative");

			if (!StringUtils.isBlank(textBody)) {
				MimeBodyPart textPart = new MimeBodyPart();
				textPart.setText(textBody, "UTF-8");
				multipart.addBodyPart(textPart);
			}

			if (!StringUtils.isBlank(htmlBody)) {
				MimeBodyPart htmlPart = new MimeBodyPart();
				htmlPart.setContent(htmlBody, "text/html; charset=UTF-8");
				multipart.addBodyPart(htmlPart);
			}
			SMTPMessage msg = new SMTPMessage(session);
			msg.setFrom(toInternetAddress(from, fromDisplayName));

			msg.setReplyTo(new Address[] { toInternetAddress(from, fromDisplayName) });
			if (replyTo != null && !replyTo.isEmpty()) {
				msg.setReplyTo(new Address[] { toInternetAddress(replyTo, replyToDisplayName) });
			}
			if (envelopeFrom != null && !envelopeFrom.isEmpty()) {
				msg.setEnvelopeFrom(envelopeFrom);
			}

			msg.setHeader("To", address);
			msg.setSubject(subject, "utf-8");
			msg.setContent(multipart);
			msg.saveChanges();
			msg.setSentDate(new Date());

			transport = session.getTransport("smtp");
			if (auth) {
				transport.connect(util.getProperty("com.ews.onlineExchange.email.user"),
						util.getProperty("com.ews.onlineExchange.email.password"));
			} else {
				transport.connect();
			}
			transport.sendMessage(msg, new InternetAddress[] { toInternetAddress(address, address) });
		} catch (MessagingException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} finally {
			if (transport != null) {
				try {
					transport.close();
				} catch (MessagingException e) {
					logger.warn("Failed to close transport", e);
				}
			}
		}
	}
	
	protected InternetAddress toInternetAddress(String email, String displayName)
			throws UnsupportedEncodingException, AddressException, EmailException {
		String debug = System.getenv( "ENV_TYPE" );
		if ( StringUtils.isBlank( debug ) || !debug.equalsIgnoreCase( "prod" ) ) {
			return new InternetAddress( email, displayName );
		}
		if (email == null || "".equals(email.trim())) {
			throw new EmailException("Please provide a valid address", null);
		}
		if (displayName == null || "".equals(displayName.trim())) {
			return new InternetAddress(email);
		}
		return new InternetAddress(email, displayName, "utf-8");
	}	
	
	
	public static void main(String[] args) {
		EmailSender sender = new EmailSender();
		try {
			sender.send("wangchangqing@sdews.com", "东营市信访局", "22222", "1111");
		} catch (EmailException e) {
			e.printStackTrace();
		}
	}
}
